package com.sunyard.layoutit.common;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

import org.restlet.data.CharacterSet;
import org.restlet.data.LocalReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

public class ApplicationConfig {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

	/**
	 * 编码
	 */
	public final static CharacterSet REST_CHARACTER_SET = CharacterSet.UTF_8;
	
	/**
	 * 编码
	 */
	public final static String FREEMARKER_CHARACTER_SET = "utf-8";
	
	/**
	 * 
	 */
	public final static Locale FREEMARKER_LOCALE = Locale.CHINA;
	
	public final static String URI_LAYOUTIT = "/index.ftl" ;
	
	public static String URI_PATTERN = "/layoutit";
	
	//默认Web资源文件路径
	public static String RESOURCES_PATH = "file:///layoutit/resources/";
	
	public static Properties getFreemarkerProperties(){
		Properties prop = new Properties();
		InputStream in = ApplicationConfig.class.getResourceAsStream("/freemarker.properties");
		try {
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return prop ;
	}
	
	public static Configuration getFreemarkerConfig() {
		Configuration config = new Configuration();
		ClassTemplateLoader classLoader = new ClassTemplateLoader(ApplicationConfig.class,"/template");
		TemplateLoader[] loaders = new TemplateLoader[] { classLoader };
		MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders);
		config.setTemplateLoader(multiLoader);
//		config.setEncoding(ApplicationConfig.FREEMARKER_LOCALE, ApplicationConfig.FREEMARKER_CHARACTER_SET);
		try {
			config.setSettings(ApplicationConfig.getFreemarkerProperties());
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return config;
	}
	
	public static LocalReference getResourcesReference(){
		File dir = new File(RESOURCES_PATH);
		return LocalReference.createFileReference(dir);
	}
	
	//是否初始化过
	private static boolean inited = false ;
	
	/**
	 * 初始化配置文件
	 */
	public static void init(){
		if(inited){
			return ;
		}
		logger.info("初始化配置文件 ...");
		Properties prop = new Properties();
		InputStream in = ApplicationConfig.class.getResourceAsStream("/config.properties");
		try {
			prop.load(in);
			URI_PATTERN = prop.getProperty("URI_PATTERN");
			RESOURCES_PATH = prop.getProperty("RESOURCES_PATH");
			inited = true ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
}
